package example.servlet;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthFilter implements Filter {
    public void init(FilterConfig filterConfig) {
    }

    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws ServletException, IOException
    {
        filterImpl((HttpServletRequest)req, (HttpServletResponse)res, chain);
    }

    private void filterImpl(HttpServletRequest req,
                            HttpServletResponse res,
                            FilterChain chain)
        throws ServletException, IOException
    {
        String path = req.getServletPath();
        System.out.println(path);

        if (req.getSession().getAttribute("user") != null ||
            "/".equals(path) ||
            "/login".equals(path) ||
            "/logout".equals(path) ||
            "/new-user".equals(path) ||
            "/example.jxt".equals(path))
        {
            chain.doFilter(req, res);
        } else {
            res.sendRedirect(
                res.encodeRedirectURL("login"));
        }
    }
}